<template>
  <g-form-wrap :title="title" :on-save-btn-click="onSaveBtnClick">
    <el-form
      ref="ruleForm"
      :model="formData"
      :rules="formRules"
      label-position="left"
      label-width="140px"
      inline
    >
      <div class="w-full">
        <el-row type="flex">
          <el-col :span="12">
            <el-form-item label="榜单名称：" prop="rankNameCn">
              <el-input
                v-model="formData.rankNameCn"
                placeholder="请输入榜单名称"
                class="edit-item"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="榜单类型：" prop="rankType">
              <g-select
                v-model="formData.rankType"
                placeholder="榜单类型："
                class="edit-item"
                :options="[
                  { id: 3, name: '主榜单' },
                  { id: 1, name: '实体榜单' },
                  { id: 2, name: '人物榜单' }
                ]"
                :filterable="true"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex">
          <el-col :span="12">
            <el-form-item label="榜单年度：" prop="rankYear">
              <el-input-number
                v-model="formData.rankYear"
                placeholder="请输入榜单年度"
                class="edit-item"
                controls-position="right"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="榜单发布机构：" prop="rankPublisher">
              <el-input
                v-model="formData.rankPublisher"
                placeholder="请输入榜单发布机构"
                class="edit-item"
                controls-position="right"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex">
          <el-col :span="12">
            <el-form-item label="榜单发布日期：" prop="rankPublishDate">
              <el-date-picker
                v-model="formData.rankPublishDate"
                :append-to-body="false"
                class="search-item"
                type="date"
                placeholder="请输入榜单发布日期"
                format="YYYY-MM-DD"
                value-format="x"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="榜单是否发布：" prop="rankPublished">
              <el-switch
                v-model="formData.rankPublished"
                size="large"
                inline-prompt
                active-text="发布"
                :active-value="1"
                inactive-text="隐藏"
                :inactive-value="2"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex">
          <el-col :span="12">
            <el-form-item label="榜单序号：" prop="rankOrder">
              <el-input-number
                v-model="formData.rankOrder"
                placeholder="请输入榜单序号"
                class="edit-item"
                controls-position="right"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="榜单描述：" prop="rankDescCn">
              <el-input
                v-model="formData.rankDescCn"
                type="textarea"
                placeholder="请输入榜单描述"
                :rows="4"
                class="edit-item"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <RankOrg v-if="isEditing" :rank="formData" />
  </g-form-wrap>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import type { Loading } from '@/components/Dialog/types'
import { useRoute, useRouter } from 'vue-router'
import { getRankByIdApi, addRankApi, updateRankApi } from '@/api/admin'
import { cloneDeep, omit } from 'lodash-es'
import store from '@/store'
import dayjs from 'dayjs'
import RankOrg from '@/views/admin/rank/orgList/index.vue'

const route = useRoute()
const router = useRouter()
const isEditing = ref(false)
const ruleForm = ref<FormInstance>()
let formData = ref<any>(<
  {
    rankId: number
    rankNameCn: string
    rankType: number
    rankYear: number
    rankPublisher: string
    rankPublishDate: string
    rankDescCn: string
    rankPublished: number
    rankOrder: number
  }
>{
    rankId: 0,
    rankNameCn: '',
    rankType: 1,
    rankYear: Number(dayjs().year() + '04'),
    rankPublisher: '',
    rankPublishDate: '',
    rankDescCn: '',
    rankPublished: 2,
    rankOrder: 0
})
const formRules = reactive<FormRules>({
    researchOrgName: [{ required: true, message: '请输入调研机构名称', trigger: 'change' }]
})
const id = route.query.id as string | number
const title = route.meta.title as string
isEditing.value = id > 0 ? true : false
// 编辑时
if (isEditing.value) {
    const getRankByIdFunc = async () => {
        const data = await getRankByIdApi(Number(id))
        // console.log('formData--before-', formData.value)
        // console.log('data---', data)
        formData.value = cloneDeep(omit(data, ['History', 'history', 'repeatKeys']))
    // console.log('formData--after-', formData.value)
    }
    getRankByIdFunc()
    store.state['orgListModule'].params.entity = { rankId: id }
}
// 保存提交
const onSaveBtnClick = async (loading: Loading) => {
    await ruleForm.value?.validate(async (valid: boolean): Promise<void> => {
        if (valid) {
            loading(true)
            if (isEditing.value) {
                // console.log('formData---update', formData.value);
                updateRankApi(formData.value).then((res) => {
                    // console.log('res---update', res);
                    if (res * 1 === 200) ElMessage.success('编辑成功')
                })
            } else {
                // console.log('formData---add', formData.value);
                addRankApi(formData.value).then((res) => {
                    // console.log('res---add', res);
                    if (res * 1 === 201) ElMessage.success('添加成功')
                })
            }
            setTimeout(() => {
                loading(false)
                router.back()
            }, 100)
        } else {
            return
        }
    })
}
const optBtnFunc = () => {
    console.log('optBtnFunc')
}
</script>
